package com.bawei.demo_shoppingcar.fragment;


import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bawei.demo_shoppingcar.R;
import com.bawei.demo_shoppingcar.activity.ReadStandardActivity;
import com.bawei.demo_shoppingcar.activity.SettingsActivity;
import com.bawei.demo_shoppingcar.activity.UserRegisterActivity;
import com.bawei.demo_shoppingcar.application.ContentData;
import com.bawei.demo_shoppingcar.view.SelectPicPopupWindow;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import static android.app.Activity.RESULT_OK;

public class MineFragment extends Fragment implements View.OnClickListener {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private RelativeLayout viewById;
    private ImageView icon;
    private TextView name;
    private GridView mine_gridView;
    private HashMap<String, Integer> map;
    private ListView mine_listView;
    private ArrayList<String> listViewData;
    private int[] images;
    private ImageView settings_pressed;
    private SelectPicPopupWindow menuWindow;

    final int TAKE_PICTURE = 1;
    int INCO_IMAGE = 0;

    public MineFragment() {
    }

    public static MineFragment newInstance(String param1, String param2) {
        MineFragment fragment = new MineFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_mine, container, false);
        initView(inflate);
        initGridViewData();
        initListViewData();
        return inflate;
    }

    private void initListViewData() {

        listViewData = new ArrayList<>();
        listViewData.add("我的订单");
        listViewData.add("邀请有礼");
        listViewData.add("兑换专区");
        listViewData.add("我的现金券");
        listViewData.add("我的抽奖单");
        listViewData.add("我收藏的商品");
        images = new int[]{
                R.drawable.my_order_icon,
                R.drawable.personal_center_contact_service_icon,
                R.drawable.my_coupon_icon,
                R.drawable.public_contact_service_icon,
                R.drawable.my_lottery_icon,
                R.drawable.my_collection_icon,

        };
        mine_listView.setAdapter(new BaseAdapter() {

            private TextView text;
            private ImageView image;

            @Override
            public int getCount() {
                return listViewData.size();
            }

            @Override
            public Object getItem(int position) {
                return listViewData.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.mine_ilst_item, parent, false);
                image = (ImageView) convertView.findViewById(R.id.mine_item_img);
                text = (TextView) convertView.findViewById(R.id.mine_item_text);
                text.setText(listViewData.get(position));
                image.setImageResource(images[position]);
                return convertView;
            }
        });


    }

    private void initGridViewData() {


        map = new HashMap<>();
        map.put("待付款", R.drawable.wait_pay);
        map.put("待发货", R.drawable.wait_send_good);
        map.put("待收货", R.drawable.wait_receive_good);
        map.put("待评价", R.drawable.wait_evaluate);
        map.put("退款", R.drawable.wait_refund);

        MyAdapter  adapter = new MyAdapter();
        mine_gridView.setAdapter(adapter);
        mine_gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 4){
                    startActivity(new Intent(getActivity(), ReadStandardActivity.class));
                }
            }
        });
    }

    private void initView(View inflate) {

        settings_pressed = (ImageView) inflate.findViewById(R.id.settings_pressed);
        mine_listView = (ListView) inflate.findViewById(R.id.mine_listView);
        mine_gridView = (GridView) inflate.findViewById(R.id.mine_gridView);
        this.viewById = (RelativeLayout) inflate.findViewById(R.id.user_log_layout);
        name = (TextView) inflate.findViewById(R.id.user_log);
        icon = (ImageView) inflate.findViewById(R.id.user_icon_default);

        this.viewById.setOnClickListener(this);
        settings_pressed.setOnClickListener(this);
        icon.setOnClickListener(this);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (!hidden) {
            boolean empty = TextUtils.isEmpty(ContentData.user_qq_image);
            if (!empty && ContentData.isLogin_QQ()) {
                name.setText(ContentData.getUser_qq_name());
                if (INCO_IMAGE == 0)
                    ImageLoader.getInstance().displayImage(ContentData.user_qq_image, icon, ContentData.options);

            } else {
                name.setText("点击登录");
                if (INCO_IMAGE == 0)
                icon.setImageResource(R.drawable.user_icon_default);
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.user_log_layout:
                if (!ContentData.isLogin_QQ())
                    startActivity(new Intent(getActivity(), UserRegisterActivity.class));
                break;

            case R.id.settings_pressed:
                startActivity(new Intent(getActivity(), SettingsActivity.class));

                break;
            case R.id.user_icon_default:
                if (ContentData.isLogin_QQ()) {
                    //实例化SelectPicPopupWindow
                    menuWindow = new SelectPicPopupWindow((Activity) getContext(), itemsOnClick);
                    //显示窗口
                    menuWindow.showAtLocation(getActivity().findViewById(R.id.mine_fragment), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置

                } else {
                    startActivity(new Intent(getActivity(), UserRegisterActivity.class));
                }
                break;
        }
    }


    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
                    break;
                case R.id.btn_pick_photo:
                    //TODO 启用相册截取图片
                    Intent intent = new Intent();
                /* 开启Pictures画面Type设定为image */
                    intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                /* 取得相片后返回本画面 */
                    startActivityForResult(intent, 2);

                    break;
                default:
                    break;
            }
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TAKE_PICTURE) {
            INCO_IMAGE = 0;
            Bitmap bm = (Bitmap) data.getExtras().get("data");
            icon.setImageBitmap(bm);//想图像显示在ImageView视图上，private ImageView img;
            File myCaptureFile = new File("sdcard/123456.jpg");
            INCO_IMAGE = 1;
            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);

                bos.flush();
                bos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (requestCode == 2) {
            Log.d("uri", "++++++++++");
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                Log.d("uri", uri.toString());
                ContentResolver cr = getActivity().getContentResolver();
                try {
                    INCO_IMAGE = 0;
                    Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                    icon.setImageBitmap(bitmap);
                    INCO_IMAGE = 1;
                } catch (FileNotFoundException e) {
                    Log.e("Exception", e.getMessage(), e);
                }
            }
        }
    }


    class MyAdapter extends  BaseAdapter{

        private ImageView image;
        private TextView text;

        @Override
        public int getCount() {
            return map.size();
        }

        @Override
        public Object getItem(int position) {
            return map.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            convertView = LayoutInflater.from(getContext()).inflate(R.layout.tab_item_view, parent, false);
            image = (ImageView) convertView.findViewById(R.id.tab_image);
            text = (TextView) convertView.findViewById(R.id.tab_text);
            Iterator<String> iterator = map.keySet().iterator();
            int res = 0;
            int i = 0;
            String texts = "";
            while (iterator.hasNext()) {

                String next = iterator.next();
                Integer integer = map.get(next);
                if (i == position) {
                    res = integer;
                    texts = next;
                }
                i++;
            }
            text.setText(texts);
            image.setImageResource(res);
            return convertView;
        }
    }
}
